<template>
  <div class="list-page">
    <EmergencyVerticalTabNav />
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="物资名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入物资名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="物资分类" prop="categoryId">
                <el-tree-select
                  v-model="queryParams.categoryId"
                  :data="categoryOptions"
                  :props="{ label: 'name', value: 'id', children: 'children', disabled: 'isParent' }"
                  placeholder="请选择物资分类"
                  clearable
                  style="width: 240px"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>

      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" border style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="物资标准名称" min-width="120" />
          <el-table-column prop="category" label="物资分类" min-width="120">
            <template #default="{ row }">
              {{ getCategoryName(row.categoryId) }}
            </template>
          </el-table-column>
          <el-table-column prop="specification" label="型号/参数" width="150" />
          <el-table-column prop="unit" label="单位" width="100" align="center" />
          <el-table-column prop="currentStock" label="当前可用数量" width="120" align="center" />
          <el-table-column prop="minStock" label="库存预警阈值" width="120" align="center" />
          <el-table-column prop="storageLocation" label="仓库编号/区域" width="150" />
          <el-table-column prop="productionBatch" label="质检批号" width="120" />
          <el-table-column prop="expirationDate" label="到期日" width="160">
            <template #default="{ row }">
              {{ row.expirationDate ? formatDateTime(row.expirationDate) : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="特殊说明" min-width="120" align="center">
            <template #default="scope">
              <span class="ellipsis-text" @click="showRemarks(scope.row)">
                {{ (scope.row.remarks || '暂无说明').slice(0, 20) }}
                {{ scope.row.remarks?.length > 20 ? '...' : '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%" class="custom-dialog" center destroy-on-close>
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="dialog-form">
          <el-form-item label="物资标准名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入物资标准名称，如'救生衣'" />
          </el-form-item>
          <el-form-item label="物资分类" prop="categoryId">
            <el-tree-select
              v-model="form.categoryId"
              :data="categoryOptions"
              :props="{ label: 'name', value: 'id', children: 'children', disabled: 'isParent' }"
              placeholder="请选择物资分类"
              :check-strictly="true"
              node-key="id"
              default-expand-all
              :render-after-expand="false"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="型号/参数" prop="specification">
            <el-input v-model="form.specification" placeholder="请输入型号/参数，如'CE认证'" />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入单位，如'箱/件/套'" />
          </el-form-item>
          <el-form-item label="当前可用数量" prop="currentStock">
            <el-input-number v-model="form.currentStock" :min="0" controls-position="right" style="width: 100%" />
          </el-form-item>
          <el-form-item label="库存预警阈值" prop="minStock">
            <el-input-number v-model="form.minStock" :min="0" controls-position="right" style="width: 100%" />
          </el-form-item>
          <el-form-item label="仓库编号/区域" prop="storageLocation">
            <el-input v-model="form.storageLocation" placeholder="请输入仓库编号/区域，如'A区3号架'" />
          </el-form-item>
          <el-form-item label="质检批号" prop="productionBatch">
            <el-input v-model="form.productionBatch" placeholder="请输入质检批号，如'储备管理'" />
          </el-form-item>
          <el-form-item label="到期日" prop="expirationDate">
            <el-date-picker v-model="form.expirationDate" type="datetime" placeholder="选择到期日" style="width: 100%" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="特殊说明" prop="remarks">
            <el-input type="textarea" v-model="form.remarks" :rows="3" placeholder="请输入特殊说明，如'防水型'" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 备注信息弹窗 -->
      <el-dialog v-model="remarksDialogVisible" title="特殊说明" width="40%" center destroy-on-close class="custom-dialog">
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">特殊说明</span>
          </div>
        </template>
        <div style="white-space: pre-wrap">{{ currentRemarks }}</div>
        <template #footer>
          <span>
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getEmergencySuppliesList,
  getEmergencySuppliesById,
  addEmergencySupplies,
  updateEmergencySupplies,
  deleteEmergencySupplies,
  getSupplyCategoryList,
  getSupplyCategoryInfo
} from '@/api/bridge/bisc/car';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import EmergencyVerticalTabNav from "./components/EmergencyVerticalTabNav.vue";

// 物资分类接口
interface CategoryItem {
  id: number | string;
  name: string;
  categoryId: number | string;
  children?: CategoryItem[];
  isParent?: boolean;
}

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const queryFormRef = ref();

// 分类数据
const categoryList = ref<CategoryItem[]>([]);
const categoryOptions = ref<CategoryItem[]>([]);
const categoryMap = ref(new Map<number | string, string>());

// 路由
const router = useRouter();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  categoryId: null
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref();
const form = ref({
  id: '',
  name: '',
  categoryId: null,
  specification: '',
  unit: '',
  currentStock: 0,
  minStock: 0,
  storageLocation: '',
  productionBatch: '',
  expirationDate: dayjs().add(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
  status: 1,
  remarks: ''
});

// 备注弹窗相关
const remarksDialogVisible = ref(false);
const currentRemarks = ref('');

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入物资标准名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择物资分类', trigger: 'change' }],
  specification: [{ required: true, message: '请输入型号/参数', trigger: 'blur' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  currentStock: [{ required: true, message: '请输入当前可用数量', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入库存预警阈值', trigger: 'blur' }],
  storageLocation: [{ required: true, message: '请输入仓库编号/区域', trigger: 'blur' }],
  expirationDate: [{ required: true, message: '请选择到期日', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 格式化日期时间
const formatDateTime = (dateTimeString: string) => {
  return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm');
};

// 获取物资列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getEmergencySuppliesList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      name: queryParams.name,
      categoryId: queryParams.categoryId
    });
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取物资列表失败', error);
    ElMessage.error('获取物资列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await getSupplyCategoryList();
    categoryList.value = res.data || [];
    // 构建分类选择器数据
    categoryOptions.value = [...categoryList.value];
    
    // 构建分类映射
    const buildCategoryMap = (categories) => {
      if (!categories || !categories.length) return;
      categories.forEach(category => {
        categoryMap.value.set(category.id, category.name);
        if (category.children && category.children.length) {
          buildCategoryMap(category.children);
        }
      });
    };
    
    buildCategoryMap(categoryList.value);
  } catch (error) {
    console.error('获取物资分类失败', error);
    ElMessage.error('获取物资分类失败');
  }
};

// 获取分类名称
const getCategoryName = (categoryId) => {
  return categoryMap.value.get(categoryId) || '-';
};

// 显示备注
const showRemarks = (row) => {
  currentRemarks.value = row.remarks || '暂无特殊说明';
  remarksDialogVisible.value = true;
};

// 搜索查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.name = '';
  queryParams.categoryId = null;
  handleQuery();
};

// 选择变更
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 页码变更
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryParams.pageNum = val;
  getList();
};

// 页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryParams.pageSize = val;
  getList();
};

// 新增物资
const handleAdd = () => {
  dialogTitle.value = '新增物资';
  form.value = {
    id: '',
    name: '',
    categoryId: null,
    specification: '',
    unit: '',
    currentStock: 0,
    minStock: 0,
    storageLocation: '',
    productionBatch: '',
    expirationDate: dayjs().add(1, 'year').format('YYYY-MM-DD HH:mm:ss'),
    status: 1,
    remarks: ''
  };
  dialogVisible.value = true;
};

// 编辑物资
const handleEdit = async (row) => {
  dialogTitle.value = '编辑物资';
  try {
    const res = await getEmergencySuppliesById(row.id);
    form.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取物资详情失败', error);
    ElMessage.error('获取物资详情失败');
  }
};

// 删除物资
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除物资"${row.name}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEmergencySupplies(row.id);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除物资失败', error);
      ElMessage.error('删除物资失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.id) {
          // 编辑
          await updateEmergencySupplies(form.value);
          ElMessage.success('更新成功');
        } else {
          // 新增
          await addEmergencySupplies(form.value);
          ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error('操作失败', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

onMounted(() => {
  getCategoryList();
  getList();
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: $bg-color-overlay;
  padding: 16px;
  border-radius: $border-radius;
}

.search-input {
  width: 300px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.ellipsis-text {
  cursor: pointer;
  color: $color-primary;
  
  &:hover {
    text-decoration: underline;
  }
}

.btn-group {
  .edit-btn,
  .cancel-btn,
  .save-btn {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 10px 20px;
    border-radius: 6px;
  }

  .edit-btn {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .cancel-btn {
    &:hover {
      background-color: #f4f4f5;
      color: #909399;
    }
  }

  .save-btn {
    padding: 10px 24px;

    &:hover {
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }
  }
}

.disabled-field {
  :deep(.el-input__inner) {
    background-color: #f8f9fa;
    border-color: #e4e7ed;
    color: #909399;
    cursor: not-allowed;
  }
}

.error-message {
  color: red;
  font-size: 14px;
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.dialog-form {
  :deep(.el-form-item__label) {
    color: var(--el-text-color-regular);
  }

  :deep(.el-input__inner) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    color: var(--el-text-color-primary);
  }
}
</style>
